import {img} from "../api/common/upload.js";
import {getCsrfToken, getFileDomain} from "../request.js";
import {fileUploadHandler} from "./layui-upload-sheet.js";

export let config = {
    // 配置项
    config: {
        language: 'zh_CN', //调用放在langs文件夹内的语言包

        width: '100%',
        height: 500,

        //选择需加载的插件
        plugins: 'print preview searchreplace autolink directionality visualblocks visualchars fullscreen image link media template code codesample table charmap hr pagebreak nonbreaking anchor insertdatetime advlist lists wordcount imagetools textpattern help emoticons autosave',

        // //选中时出现的快捷工具，与插件有依赖关系
        toolbar: 'code undo redo restoredraft | cut copy paste pastetext | forecolor backcolor bold italic underline strikethrough link anchor | alignleft aligncenter alignright alignjustify outdent indent | \
                     styleselect formatselect fontselect fontsizeselect | bullist numlist | blockquote subscript superscript removeformat | \
                     table image media charmap emoticons hr pagebreak insertdatetime print preview | fullscreen | lineheight',

        // 阻止关闭或刷新页面，系统弹出未保存
        autosave_ask_before_unload: false,

        // 处理图片url
        relative_urls: true,
        document_base_url: getFileDomain(),

        // 上传文件自定义处理
        images_upload_handler: (blobInfo, success, fail) => {
            let form = new FormData();
            form.append('img', blobInfo.blob(), blobInfo.filename());

            // 上传图片，配置项
            img(form, {
                cache: false,
                processData: false,
                contentType: false,

                headers: {
                    'X-CSRF-TOKEN': getCsrfToken()
                }
            }).then(res => {
                if (200 === res.code) {
                    success(res.data.input);
                } else {
                    fail(`上传错误：${res.msg}`);
                }
            }).catch(res => {
                fail(`上传错误：${res}`);
            });
        },

        // 文件上传图标
        file_picker_types: 'media',

        // 视频格式
        file_format: 'mp4|webm|ogg',

        /**
         * 文件上传回调
         *
         * @param cb        回调方法
         * @param value     值
         * @param meta      类型
         */
        file_picker_callback: function (cb, value, meta) {
            if (meta.filetype === 'media') {
                // 文件格式
                let format = this.settings.file_format.split('|').map((v) => {
                    return '.' + v;
                }).join(', ');

                let input = document.createElement('input');
                input.setAttribute('type', 'file');
                input.setAttribute('accept', format);
                input.click();

                input.onchange = async function () {
                    let index = layer.load(2);

                    let result = await fileUploadHandler(0, this.files[0]);
                    layer.close(index);
                    if (result.code !== 200) {
                        return dialog("文件上传失败，请重新尝试");
                    }

                    cb(result.data.input);
                }
            }
        },

        // 实时预览
        media_live_embeds: true,
    }
};
